<template>
  <div class="report-container"
       style="width:100%"
       id="otherrevenue-des">
    <Row type='flex'
         justify="space-between"
         class="coinrevenue-list-edit">
      <Row type='flex'
           align='middle'>
        <Col>
        <span class="concrete-data">时间：</span>
        <datePickerYmd @on-change="searchStatistical"
                       :selectDateType.sync='selectDateType'
                       :dateOption="dateOption"
                       :dataType='dataType'
                       v-model="timeDate"
                       style="display:inline-block"></datePickerYmd>
        </Col>
        <Row type='flex'
             align='middle'
             class="export-btn">
          <Col><span>门店名称：</span></Col>
          <Col>
          <!-- <Select v-model="searchObj.shopId"
                  multiple
                  filterable
                  :max-tag-count="1"
                  class="select-shop-item"
                  @on-change="selectshop"
                  :max-tag-placeholder="maxTagPlaceholder"
                  style="width:210px">
            <Option v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select> -->
          <!-- <vueTreeselectShop :shopList.sync="searchObj.shopId"
                             :statusList.sync="statusList"
                             @id-change="searchStatistical"
                             permissionCode="moms:report:otherrevenue"
                             v-model="testValue"></vueTreeselectShop> -->
          <vueTreeselectChoice :multiple="true"
                               ref="vueTreeselectChoice"
                               @input="handleShop"
                               @on-api-finish="apiFinish"
                               permissionCode="moms:report:otherrevenue"
                               v-model="ShopValue"></vueTreeselectChoice>
          </Col>
          <Col>
          <Button type="primary"
                  class="coinrevenue-btn export-btn"
                  style="width:80px;"
                  @click="searchStatistical">查询</Button>
          </Col>
        </Row>
      </Row>
      <Col class="statistical">
      <Dropdown trigger="click"
                class="coinrevenue-btn export-btn"
                style="margin-right:-90px;width:170px"
                @on-click="DropdownItemn"
                v-if="hasPermission('moms:report:otherrevenueexport')">
        <Button class="check_all"
                style="width:80px;margin-right:20px">导出
          <Icon type="ios-arrow-down"></Icon></Button>
        <DropdownMenu slot="list"
                      style="text-align:center">
          <DropdownItem name="todayExtraIncome">今日另收表</DropdownItem>
          <DropdownItem name="todayExtraIncomeGroupDetail">团购明细表</DropdownItem>
          <DropdownItem name="todayExtraIncomeLeaseDetail">租赁明细表</DropdownItem>
          <DropdownItem name="todayExtraIncomeBankcardDetail">新项目明细表</DropdownItem>
          <DropdownItem name="todayExtraIncomeNonmemberDepositDetail">非会员卡押金明细表</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      </Col>
    </Row>
    <Table stripe
           ref="rowSpanTable"
           :height="this.tableHeight"
           :loading="isloading"
           class="table-list"
           border
           :columns="columns"
           :data="resData">
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:otherrevenue"
                 v-if="hasPermission('moms:report:otherrevenueexport')"></down-center>
  </div>
</template>
<script>
import '../../report.less'
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { statisticalDemand } from '@/api/report/finance'
import { formatAmount } from '@/libs/tools'
// import { blobToXls } from '@/libs/blobToXls'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
import dayjs from 'dayjs'
import DownCenter from '@/view/components/down-center/index.vue'
export default {
  name: 'report_finance_otherrevenue',
  components: { vueTreeselectChoice, datePickerYmd, DownCenter },
  data () {
    return {
      dataChoose: 'day',
      shopName: null,
      options: [],
      isloading: false,
      value: null,
      ShopValue: [],
      statusList: false,
      tableHeight: 0,
      testValue: [],
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      total: 0,
      selectDateType: 'date',
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      timeDate: [dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'), dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00')],
      optionsStartTimeDay: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      },
      shopList: [],
      searchObj: {
        shopId: [],
        offset: 1,
        limit: 10
      },
      columns: [
        { title: '门店', key: 'shopName', align: 'center' },
        { title: '合计(元)', key: 'totalAmount', align: 'center' },
        {
          title: '团购收款金额(元)',
          align: 'center',
          key: 'groupAmount',
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: '#2d8cf0',
                  cursor: 'pointer',
                  textDecoration: 'underline #2d8cf0'
                },
                on: {
                  click: () => {
                    this.jumpgroup(params.row.shopId)
                  }
                }
              }, params.row.groupAmount)
            ])
          }
        },
        {
          title: '租赁(元)',
          key: 'rent',
          align: 'center',
          children: [
            { title: '租金(元)', key: 'rentAmount', align: 'center' },
            { title: '押金(元)', key: 'depositAmount', align: 'center' },
            {
              title: '租赁合计(元)',
              align: 'center',
              key: 'rentAndDepositAmount',
              render: (h, params) => {
                return h('div', [
                  h('span', {
                    style: {
                      color: '#2d8cf0',
                      cursor: 'pointer',
                      textDecoration: 'underline #2d8cf0'
                    },
                    on: {
                      click: () => {
                        this.jumprent(params.row.shopId)
                      }
                    }
                  }, params.row.rentAndDepositAmount)
                ])
              }
            }
          ]
        },
        {
          title: '非会员卡押金(元)',
          align: 'center',
          key: 'nonmemberAmount',
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: '#2d8cf0',
                  cursor: 'pointer',
                  textDecoration: 'underline #2d8cf0'
                },
                on: {
                  click: () => {
                    this.jumnonmember(params.row.shopId)
                  }
                }
              }, params.row.nonmemberAmount)
            ])
          }
        },
        {
          title: '新项目收款金额(元)',
          align: 'center',
          key: 'bankcardAmount',
          render: (h, params) => {
            return h('div', [
              h('span', {
                style: {
                  color: '#2d8cf0',
                  cursor: 'pointer',
                  textDecoration: 'underline #2d8cf0'
                },
                on: {
                  click: () => {
                    this.jumpbankcard(params.row.shopId)
                  }
                }
              }, params.row.bankcardAmount)
            ])
          }
        }
      ],
      resData: []
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      return this.timeDate[1]
    }
  },
  mounted () {
    // this.getShopList()
  },
  methods: {
    // 导出表格
    DropdownItemn (val) {
      if (!this.searchObj.shopId.length) return this.$Message.error(`请选择门店列表`)
      this.$refs.downCenterRef.addTask({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        dateType: { year: 2, month: 1, date: 0 }[this.selectDateType],
        taskModule: val
      })
    },
    filtersResData (data) {
      data.map(ele => {
        Object.keys(ele).forEach(key => {
          if (key !== 'shopName' && key !== 'shopId') ele[key] = formatAmount(ele[key])
        })
      })
      return data
    },
    // 团购明细
    jumpgroup (idx) {
      localStorage.setItem('group', JSON.stringify({ id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_finance_otherrevenue_group_detail',
          params: { id: 1 }
        })
      }
    },
    // 租赁明细
    jumprent (idx) {
      localStorage.setItem('rent', JSON.stringify({ id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_finance_otherrevenue_rent_detail',
          params: { id: 1 }
        })
      }
    },
    // 非会员押金
    jumnonmember (idx) {
      localStorage.setItem('nonmember', JSON.stringify({ id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_finance_otherrevenue_deposit_detail',
          params: { id: 1 }
        })
      }
    },
    // 新项目
    jumpbankcard (idx) {
      localStorage.setItem('bankcard', JSON.stringify({ id: [idx], type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.$router.push({
          name: 'report_finance_otherrevenue_card_detail',
          params: { id: 1 }
        })
      }
    },
    getRevenue () {
      this.isloading = true
      this.tableHeight = 0
      statisticalDemand({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        // shopIds: ['aaae3be8-0323-4208-b903-638d4d8949c5'],
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit
      }).then(res => {
        this.isloading = false
        if (res.data.status === 200) {
          this.total = res.data.totalCount
          if (res.data.data && res.data.data.length >= 14) {
            this.tableHeight = 520
          }
          this.resData = res.data.data ? this.filtersResData(res.data.data) : []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    searchStatistical () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getRevenue()
      }
    },
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      this.searchStatistical()
    },
    apiFinish () {
      this.ShopValue = null
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      this.getRevenue()
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      this.getRevenue()
    }
  }
}
</script>
<style>
#otherrevenue-des .statistical .ivu-select-dropdown {
  left: -67px !important;
}
</style>
